<template>
    <a-card
        id="mysql-test"
        hoverable
        :tabList="tabList"
        :activeTabKey="tabKey"
        @tabChange="onTabChange"
    >
        <template>
            <keep-alive>
                <template v-if=" tabKey == 'input' ">
                    <div class="input-area">
                        <div class="tool-bar-area">
                            <a-button size="small" @click="sqlQuery">查询</a-button>
                        </div>
                        <a-textarea v-model="statement"></a-textarea>
                    </div>
                </template>

                <template v-else-if=" tabKey == 'result' ">
                    <div class="result-frame">
                        <div class="result-selecter">
                            <a-radio-group size="small" v-model="sql_current_index">
                                <a-radio-button
                                    v-for="n in sql_source_result.length"
                                    :value="n-1"
                                    :key="n"
                                >{{ n }}</a-radio-button>
                            </a-radio-group>
                        </div>

                        <div class="result-area" @scroll="resultScroll">
                            <div>

                                <table class="result-table">
                                    <thead>
                                        <tr>
                                            <th
                                                v-for="({title}, index) in sql_columns"
                                                :key="title"
                                                :style="{top:result_scroll_top+'px'}"
                                            >
                                                <div class="float-title">{{ title }}</div>
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="(row, index) in sql_result" :key="index">
                                            <td
                                                v-for="({dataIndex}, c_idx) in sql_columns"
                                                :key="index+'_'+c_idx"
                                            >{{ row[dataIndex] }}</td>
                                        </tr>
                                    </tbody>
                                </table>
                                
                            </div>
                        </div>
                    </div>
                </template>
            </keep-alive>
        </template>
    </a-card>
</template>

<style lang="less">
#mysql-test {
    height: 100%;
    display: flex;
    flex-direction: column;

    // > .ant-card-head {
    // }
    > .ant-card-body {
        position: relative;
        flex: 1;
        padding: 15px;

        .input-area {
            height: 100%;
            width: 100%;
            display: flex;
            flex-direction: column;

            .tool-bar-area {
                text-align: right;
                margin-bottom: 8px;
            }

            textarea {
                flex: 1;
                resize: none;
            }
        }

        .result-frame {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;

            .result-selecter {
                flex: 0;
                margin-bottom: 8px;
            }

            .result-area {
                flex: 1;
                overflow: auto;
                height: 1px;

                @border-color: rgb(179, 179, 179);
                table.result-table {
                    min-width: 100%;
                    border: 1px solid @border-color;
                    > thead {
                        > tr {
                            background: #dddddd;
                            > th {
                                position: relative;
                                border: 1px solid @border-color;
                                .float-title {
                                    display: block;
                                    margin: -2px -2px;
                                    background: #dddddd;
                                    border: 1px solid @border-color;
                                }
                            }
                        }
                    }
                    > tbody {
                        > tr {
                            &:nth-child(2n) {
                                background: #eee;
                            }
                            > td {
                                padding: 2px 2px;
                                border: 1px solid @border-color;
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>

<script lang="ts">
import _ from "lodash";
import { Component, Vue, Prop } from "vue-property-decorator";
import { ipcRenderer } from "electron";
import { MysqlError, FieldInfo } from "mysql";
import { Field } from "ant-design-vue/types/form/form";

const CONN_KEY = "mysql-test-01";

@Component
export default class MySQL extends Vue {
    /** 标签页信息 */
    public tabList = [
        { key: "input", tab: "输入" },
        { key: "result", tab: "结果" }
    ];

    /** 当前标签页 */
    public tabKey = "input";

    public statement: string = "select * from users;"; // "select now();";
    /** 查询结果的字段数据源 */
    public sql_source_field: (FieldInfo[] | null)[] = [];
    /** 查询结果的数据源 */
    public sql_source_result: Object[][] = [];
    /** 当前结果的索引 */
    public sql_current_index: number = 0;

    get sql_columns(): Object[] {
        let fields = this.sql_source_field[this.sql_current_index];
        if (_.isNull(fields) || _.isEmpty(fields)) {
            return _.map(["key", "value"], x => ({
                title: x,
                dataIndex: x
            }));
        } else {
            return _.map(fields, f => ({
                title: f.name,
                dataIndex: f.name
            }));
        }
    }

    get sql_result(): Object[] {
        let ret = [];
        let fields = this.sql_source_field[this.sql_current_index];
        let results = this.sql_source_result[this.sql_current_index];
        if (_.isEmpty(fields)) {
            if (_.has(results, "errno")) {
                ret = _.map(
                    ["code", "errno", "index", "sqlState", "sqlMessage", "sql"],
                    x => ({
                        key: x,
                        value: _.get(results, x)
                    })
                );
            } else {
                ret = _.map(
                    [
                        "affectedRows",
                        "changedRows",
                        "fieldCount",
                        "insertId",
                        "message",
                        "protocol41",
                        "serverStatus",
                        "warningCount"
                    ],
                    x => ({
                        key: x,
                        value: _.get(results, x)
                    })
                );
            }
        } else {
            ret = results;
        }
        return ret;
    }

    public result_scroll_top: number = 0;

    async created() {
        let ret_key = await ipcRenderer.sendSync("mysql-conn", {
            key: CONN_KEY,
            host: "120.79.202.188",
            user: "test5_1",
            password: "kfhWmyEzhWEs6HTw",
            database: "test5_1"
        });
    }

    onTabChange(key: string) {
        this.tabKey = key;
    }

    async sqlQuery() {
        console.log("开始查询：" + new Date().toISOString());

        let {
            status,
            message,
            error,
            fields = [],
            results = []
        }: {
            status: string;
            message: string;
            error: MysqlError;
            fields: FieldInfo[][] | FieldInfo[];
            results: Object[][] | Object[];
        } = await ipcRenderer.sendSync("mysql-query", {
            key: CONN_KEY,
            statement: this.statement,
            values: null
        });

        // /*
        console.log({
            status,
            message,
            error,
            fields,
            results
        });
        // */

        if (status == "success") {
            // 判断是否为复式结果
            if (
                _.isArray(fields) &&
                (_.isNull(fields[0]) || _.isArray(fields[0]))
            ) {
                this.sql_source_field = fields as FieldInfo[][];
                this.sql_source_result = results as Object[][];
            } else {
                this.sql_source_field = [fields as FieldInfo[]];
                this.sql_source_result = [results as Object[]];
            }
            this.sql_current_index = 0;
        } else {
            this.sql_source_field = [null];
            this.sql_source_result = [[error]];

            this.sql_current_index = 0;
        }
        this.tabKey = "result";
    }

    resultScroll(event: Event) {
        if (event.srcElement != null) {
            this.result_scroll_top = event.srcElement.scrollTop;
        } else {
            this.result_scroll_top = 0;
        }
    }
}
</script>

